<template>
  <div>
    <!-- <h1>QueryView</h1> -->
    <!--  -->
    <el-form inline size="small">
      <el-form-item label="日期范围">
        <el-date-picker
          v-model="form.start"
          type="date"
          placeholder="开始日期"
          :clearable="false"
        />
        <span style="padding: 0 8px">至</span>
        <el-date-picker
          v-model="form.end"
          type="date"
          placeholder="结束日期"
          :clearable="false"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :disabled="isInvalid" @click="handleQuery">
          <el-icon><Search /></el-icon>
          <span>查询</span>
        </el-button>
        <el-button
          type="success"
          :disabled="tableData.length == 0"
          @click="handleExport(tableData)"
        >
          <el-icon><Download /></el-icon>
          <span>导出</span>
        </el-button>
      </el-form-item>
    </el-form>
    <!-- <pre>tableData:</pre> -->
    <!-- <pre>{{ tableData }}</pre> -->
    <el-table :data="tableData" size="small">
      <el-table-column prop="acid" label="呼号" min-width="80px" />
      <el-table-column prop="companyName" label="航司" min-width="60px" />
      <el-table-column prop="seat" label="席位" min-width="60px" />
      <el-table-column label="频率" min-width="100px">
        <template #default="scope">
          <span>{{ scope.row.frequency }}MHz</span>
        </template>
      </el-table-column>
      <el-table-column prop="moment" label="事件时间" min-width="160px" />
      <el-table-column prop="stageName" label="飞行阶段" min-width="80px" />
      <el-table-column
        prop="finalPosition"
        label="五边位置"
        min-width="160px"
      />
      <el-table-column label="指令速度" min-width="80px">
        <template #default="scope">
          <span>{{ scope.row.speedCleared }}kt</span>
        </template>
      </el-table-column>
      <el-table-column label="执行速度" min-width="80px">
        <template #default="scope">
          <span>{{ scope.row.speedExecuted }}kt</span>
        </template>
      </el-table-column>
      <el-table-column label="产生的影响" min-width="360px">
        <template #default="scope">
          <span
            :style="{
              color:
                scope.row.effectCode == 0
                  ? 'var(--el-color-info)'
                  : scope.row.effectCode == 1
                  ? 'var(--el-text-color-regular)'
                  : scope.row.effectCode == 2
                  ? 'var(--el-color-warning)'
                  : 'var(--el-color-danger)',
            }"
          >
            {{ scope.row.effectName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="中止进近" min-width="160px">
        <template #default="scope">
          <span
            :style="{
              color:
                scope.row.missedApproachCode == 0
                  ? 'var(--el-color-info)'
                  : 'var(--el-color-warning)',
            }"
          >
            {{ scope.row.missedApproachName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="描述" min-width="40px">
        <template #default="scope">
          <el-button
            class="vibrate-slight"
            v-if="scope.row.description != ''"
            type="primary"
            link
            @click="handleShowDescription(scope.row.description)"
          >
            <el-icon><InfoFilled /></el-icon>
            <!-- <span>查看</span> -->
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="记录时间" min-width="160px" />
      <el-table-column prop="createdIP" label="信息来源" min-width="120px" />
    </el-table>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessageBox, ElNotification } from "element-plus";
import axios from "axios";
import dayjs from "dayjs";
import * as ExcelJS from "exceljs/dist/exceljs.min.js";
import FileSaver from "file-saver";
import OptionDataStatics from "./OptionDataStatics.js";

const form = ref({
  start: new Date(),
  end: new Date(),
});

const isInvalid = computed(() =>
  dayjs(form.value.start).isAfter(form.value.end, "day")
);

const content = ref([]);
const tableData = ref([]);

const handleQuery = () => {
  axios
    .post("api/journal_speed.php", {
      method: "query",
      payload: {
        start: dayjs(form.value.start).format("YYYY-MM-DD") + " 00:00:00",
        end: dayjs(form.value.end).format("YYYY-MM-DD") + " 23:59:59",
      },
    })
    .then((response) => {
      if (response.data.status == 1) {
        tableData.value = new Array();
        content.value = response.data.content;
        tableData.value = getTableData(response.data.content);
        ElNotification({
          title: "已完成",
          message: "查询到" + response.data.content.length + "条记录",
          type: "success",
        });
      } else {
        ElNotification({
          title: "查询出错了",
          type: "error",
        });
      }
    })
    .catch((error) => {
      console.error("SpeedDevidationQuery", error);
      ElNotification({
        title: "查询出错了",
        message: error.message,
        type: "error",
      });
    });
};

const getTableData = (content) => {
  return content.map((item) => {
    return {
      acid: item.acid,
      companyCode: item.company,
      companyName: getLabelByValue("companies", item.company),
      seat: item.seat,
      frequency: item.frequency.replace(/\.?0+$/, ""),
      moment: item.moment,
      speedCleared: item.speed,
      speedExecuted: item.speed2,
      stageCode: item.stage,
      stageName: getLabelByValue("stages", item.stage),
      finalPosition: item.stage == 3 ? item.pos + "nm" : "不涉及",
      effectCode: item.effect,
      effectName: getLabelByValue("effects", item.effect),
      missedApproachCode: item.mis,
      missedApproachName:
        item.effect == 3
          ? getLabelByValue("missedApproachOptions", item.mis)
          : "不涉及",
      description: item.description,
      createdAt: item.created,
      createdIP: item.ip,
      number: item.number,
    };
  });
};

const getLabelByValue = (optKey, val) => {
  let arr = OptionDataStatics[optKey].filter((cell) => cell.value == val);
  if (arr.length > 0) return arr[0].label;
  return "";
};

const handleShowDescription = (description) => {
  ElMessageBox({
    title: "事件描述",
    message: description,
    type: "info",
    showClose: false,
    showConfirmButton: false,
    showCancelButton: false,
  });
};

const handleExport = (tableData) => {
  let fileName = "调速偏差记录导出@" + dayjs().format("YYYYMMDD_HHmmss");
  const workbook = new ExcelJS.Workbook();
  // 明细表
  const worksheet = workbook.addWorksheet("调速偏差记录", {
    views: [{ state: "frozen", xSplit: 1, ySplit: 1 }],
  });
  worksheet.columns = [
    { header: "呼号", key: "acid", width: 12 },
    { header: "航司", key: "companyName", width: 10 },
    { header: "航司代码", key: "companyCode", width: 10 },
    { header: "席位", key: "seat", width: 10 },
    { header: "频率", key: "frequency", width: 10 },
    { header: "事件时间", key: "moment", width: 30 },
    { header: "飞行阶段", key: "stageName", width: 10 },
    { header: "五边位置", key: "finalPosition", width: 10 },
    { header: "指令速度", key: "speedCleared", width: 10 },
    { header: "执行速度", key: "speedExecuted", width: 10 },
    { header: "产生的影响", key: "effectName", width: 50 },
    { header: "中止进近", key: "missedApproachName", width: 50 },
    { header: "补充描述", key: "description", width: 50 },
    { header: "提交时间", key: "createdAt", width: 30 },
    { header: "来源IP", key: "createdIP", width: 15 },
    { header: "序号#", key: "number", width: 10 },
    { header: "航司#", key: "companyCode", width: 10 },
    { header: "阶段#", key: "stageCode", width: 10 },
    { header: "影响#", key: "effectCode", width: 10 },
    { header: "MIS#", key: "missedApproachCode", width: 10 },
  ];

  tableData.forEach((cell) => worksheet.addRow(cell));

  worksheet.properties.defaultRowHeight = 15;
  worksheet.eachRow((row, rowNumber) => {
    row.eachCell((cell, colNumber) => {
      cell.alignment = {
        vertical: "middle",
        horizontal: "center",
        wrapText: true,
      };
      if (rowNumber == 1) {
        cell.font = { size: 12, bold: true };
      } else {
        cell.font = { size: 12 };
      }
    });
  });

  workbook.xlsx.writeBuffer().then((buffer) => {
    const fileData = new Blob([buffer], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8",
    });
    FileSaver.saveAs(fileData, fileName + ".xlsx");
    ElNotification({
      title: "已保存为Excel文档",
      message: fileName + ".xlsx",
      type: "success",
    });
  });
};

onMounted(() => {
  form.value.start = new Date();
  form.value.end = new Date();
});
</script>

<style scoped>
@import "@/styles/vibrate.css";
</style>
